﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Studio77.GuessTheWordsForWP7.Views;
using Studio77.GuessTheWordsForWP7.Core;
using Studio77.GuessTheWordsForWP7.Entity;
using System.Windows.Threading;
using Studio77.GuessTheWordsForWP7.Util;
using System.Windows.Media.Imaging;
using Coding4Fun.Phone.Controls;
using Microsoft.Phone.Tasks;
using CN.SmartMad.Ads.WindowsPhone.WPF;

namespace Studio77.GuessTheWordsForWP7
{
    public partial class GamePage : PhoneApplicationPage
    {
        public static GamePage GamePageInstance;

        CharacterBlock[,] blocks;
        CharacterBlock selectedBlock = null;
        List<CharacterBlock> senseBlocks_horizon;
        List<CharacterBlock> senseBlocks_vertical;
        int currentRow { get; set; }
        int currentColumn { get; set; }
        bool isPreviousRight = true;
        DispatcherTimer timer;
        int saveSecondCount = 0;
        //private AsyncEventHandler lb_SubmitScoreCompleted;
        bool isShowingTip;
        int tipSeconds = 1;
        List<String> scoreStrs = new List<string>();
        Random r = new Random(DateTime.Now.Millisecond);

        bool isPause = false;

        object pauseSyncObj = new object();

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            lock (pauseSyncObj)
            {
                if (!isPause)
                {
                    //设置暂停
                    isPause = true;
                    this.bdrPause.Visibility = System.Windows.Visibility.Visible;

                    this.txtPauseCurrentStageName.Text = "关卡-" + StageManager.Instance.LastStage;
                    this.txtPauseScore.Text = "得分：" + StageManager.Instance.getCurrentStageData().Score;
                    this.txtPauseCompleteInfo.Text = "完成情况：" + StageManager.Instance.getCurrentStageData().ComplateCount + "/"
                        + StageManager.Instance.mapInfos[StageManager.Instance.LastStage].wordsCount;
                    this.txtPauseTime.Text = "累计用时：" + (StageManager.Instance.getCurrentStageData().TotalSeconds / 60).ToString() + "'"
                        + (StageManager.Instance.getCurrentStageData().TotalSeconds % 60);
                }
                else
                {
                    isPause = false;
                    this.bdrPause.Visibility = System.Windows.Visibility.Collapsed;
                }
                e.Cancel = true;
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            timer.Stop();
            StageManager.Instance.saveStageDatas();

            //提交分数
            //if (XLiveGameManager.CurrentSession != null && XLiveGameManager.CurrentSession.IsValid)
            //{
            //    int sum = 0;
            //    foreach (var item in StageManager.Instance.stageDatas.Values)
            //    {
            //        sum += item.Score;
            //    }
            //    if (StageManager.Instance.LastScore < sum)
            //    {
            //        Leaderboard lb = new Leaderboard(XLiveGameManager.CurrentSession, "3350edd7-0153-4404-aacb-9e6e54d1f677");
            //        lb.SubmitScoreCompleted += new AsyncEventHandler(ScoreSubmitCompleted);
            //        lb.SubmitScore(sum);
            //        StageManager.Instance.LastScore = sum;
            //    }
            //}
        }

        DispatcherTimer mokaAdsSwitchTimer;
        int currentMokaAdIndex = 0;
        int totalMokaAdCount = 2;

        bool usemoka = true;

        public GamePage()
        {
            InitializeComponent();
            GamePageInstance = this;
            this.Loaded += new RoutedEventHandler(GamePage_Loaded);

            scoreStrs.Add("再接再厉！");
            scoreStrs.Add("厉害,你可以去参加电视节目了");
            scoreStrs.Add("牛X，牛X");
            scoreStrs.Add("加油！继续填字");
            scoreStrs.Add("不错哦！快爱上填字了吧");
            scoreStrs.Add("你确定没有用百度？！");
            scoreStrs.Add("你确定没有用搜索引擎？");
            scoreStrs.Add("帅！你是冠军");
            scoreStrs.Add("我的神啊！这你都能答对");
            scoreStrs.Add("偶像！继续");
        }

        void GamePage_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= new RoutedEventHandler(GamePage_Loaded);
            //this.BackKeyPress += new EventHandler<System.ComponentModel.CancelEventArgs>(GamePage_BackKeyPress);
            this.cvsBlocks.MouseLeftButtonDown += new MouseButtonEventHandler(cvsBlocks_MouseLeftButtonDown);
            string stageIndexStr = string.Empty;
            NavigationContext.QueryString.TryGetValue("stageIndex", out stageIndexStr);
            if (stageIndexStr != string.Empty)
            {
                int stageIndex = int.Parse(stageIndexStr);
                StageManager.Instance.LastStage = stageIndex;
                InitStage(stageIndex);
            }

            //魔卡广告切换Timer
            mokaAdsSwitchTimer = new DispatcherTimer();

            //获取间隔参数
            int intervalSec = 30;
            string secStr = UmengSDK.UmengAnalytics.GetOnlineParam("moka_banner_switch_sec");
            if (!int.TryParse(secStr, out intervalSec))
            {
                intervalSec = 30;
            }

            mokaAdsSwitchTimer.Interval = TimeSpan.FromSeconds(intervalSec);
            mokaAdsSwitchTimer.Tick += mokaAdsSwitchTimer_Tick;
            mokaAdsSwitchTimer.Start();

            bool useSmartmad = true;
            String usemokaStr = UmengSDK.UmengAnalytics.GetOnlineParam("usemoka");
            //0-关闭 1-同时开启 2-开启banner 3-开启开屏
            if (usemokaStr == "1" || usemokaStr == "2")
            {
                usemoka = true;
                if (StageManager.Instance.TurnMoka)
                {
                    //移动moka到最前面，而且不显示亿动
                    LayoutRoot.Children.Remove(imgBanner);
                    LayoutRoot.Children.Add(imgBanner);
                    useSmartmad = false;
                }
                StageManager.Instance.TurnMoka = !StageManager.Instance.TurnMoka;
                currentMokaAdIndex = 0;
                switchMokaAdImage();
            }
            else if (usemokaStr == "0" || usemokaStr == "3")
            {
                this.imgBanner.Visibility = System.Windows.Visibility.Collapsed;
                usemoka = false;
            }
            else
            {
                usemoka = false;
            }


            if (useSmartmad)
            {
                InitSmartMadAd();
                initMsnAd();
                adControlMicrosoft.ErrorOccurred += adControlMicrosoft_ErrorOccurred;
            }
            else
            {
                gridMsnAd.Visibility = System.Windows.Visibility.Collapsed;
            }

            //判断弹出去评价的提示
            GotoMarketToComment();
        }

        void adControlMicrosoft_ErrorOccurred(object sender, Microsoft.Advertising.AdErrorEventArgs e)
        {
            adControlMicrosoft.ErrorOccurred -= adControlMicrosoft_ErrorOccurred;
            //发生错误，立即取消显示
            Dispatcher.BeginInvoke(() =>
            {
                if (adControlMicrosoft != null)
                {
                    this.LayoutRoot.Children.Remove(adControlMicrosoft);
                    adControlMicrosoft = null;
                }
            });
        }

        /// <summary>
        /// 更新魔卡广告的banner
        /// </summary>
        private void switchMokaAdImage()
        {
            BitmapImage bitmap = new BitmapImage(new Uri(@"\Images\banner" + (currentMokaAdIndex + 1).ToString() + ".jpg", UriKind.RelativeOrAbsolute));
            this.imgBanner.Source = bitmap;
        }

        void mokaAdsSwitchTimer_Tick(object sender, EventArgs e)
        {
            currentMokaAdIndex++;
            currentMokaAdIndex = currentMokaAdIndex % totalMokaAdCount;
            switchMokaAdImage();
        }

        /// <summary>
        /// 去市场评价
        /// </summary>
        private void GotoMarketToComment()
        {
            if (!StageManager.Instance.IsCommented &&
                ((StageManager.Instance.LaunchCount >= 5 && StageManager.Instance.LaunchCount < 10) || StageManager.Instance.LaunchCount % 15 == 0))
            {
                if (MessageBox.Show("游戏还满意吗？去商店给个好评吧。谢谢您对开发者的支持！", "去评论吧！", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
                    marketplaceReviewTask.Show();
                    StageManager.Instance.IsCommented = true;
                }
            }
        }

        //void ScoreSubmitCompleted(object sender, AsyncEventArgs e)
        //{
        //    if (e.Result.ReturnValue)
        //    {
        //        // Succeed
        //    }
        //    else
        //    {
        //        //MessageBox.Show(e.Result.ErrorMessage);
        //    }

        //}

        void cvsBlocks_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Point point = e.GetPosition(this.cvsBlocks);
            int column = (int)point.X / 44;
            int row = (int)point.Y / 44;
            changeSelectBlock(column, row);

        }

        private void changeSelectBlock(int column, int row)
        {
            if (row >= 0 && row < 10 && column >= 0 && column < 10)
            {

                if (blocks[row, column].CurrentType != BlockType.NoChar)
                {
                    if (selectedBlock != null)
                    {
                        selectedBlock.changeBackgroundType(0);
                    }

                    blocks[row, column].changeBackgroundType(2);
                    selectedBlock = blocks[row, column];

                    currentRow = row;
                    currentColumn = column;

                    findSenseBlocks(row, column);

                    // show tip
                    setTip(selectedBlock.HorizontalTip,
                            selectedBlock.VerticalTip);
                }
                else
                {
                    clearSelection();
                }
                isPreviousRight = true;
            }
        }

        /// <summary>
        /// 查找感应块
        /// </summary>
        /// <param name="row"></param>
        /// <param name="column"></param>
        private void findSenseBlocks(int row, int column)
        {

            // 恢复状态
            foreach (CharacterBlock block in senseBlocks_horizon)
            {
                if (block.CurrentType != BlockType.Selected)
                {
                    block.changeBackgroundType(BlockType.Normal);
                }
            }

            foreach (CharacterBlock block in senseBlocks_vertical)
            {
                if (block.CurrentType != BlockType.Selected)
                {
                    block.changeBackgroundType(BlockType.Normal);
                }
            }

            // 清空
            senseBlocks_horizon.Clear();
            senseBlocks_vertical.Clear();

            // 横向向左
            if (column > 0)
            {
                for (int i = column - 1; i >= 0; i--)
                {
                    if (blocks[row, i].CurrentType == BlockType.NoChar)
                    {
                        break;
                    }
                    senseBlocks_horizon.Add(blocks[row, i]);
                }
            }
            // 横向向右
            if (column < 10 - 1)
            {
                for (int i = column + 1; i < 10; i++)
                {
                    if (blocks[row, i].CurrentType == BlockType.NoChar)
                    {
                        break;
                    }
                    senseBlocks_horizon.Add(blocks[row, i]);
                }
            }
            // 竖向向上
            if (row > 0)
            {
                for (int i = row - 1; i >= 0; i--)
                {
                    if (blocks[i, column].CurrentType == BlockType.NoChar)
                    {
                        break;
                    }
                    senseBlocks_vertical.Add(blocks[i, column]);
                }
            }
            // 竖向向下
            if (row < 10 - 1)
            {
                for (int i = row + 1; i < 10; i++)
                {
                    if (blocks[i, column].CurrentType == BlockType.NoChar)
                    {
                        break;
                    }
                    senseBlocks_vertical.Add(blocks[i, column]);
                }
            }

            // 切换显示状态
            foreach (CharacterBlock block in senseBlocks_horizon)
            {
                block.changeBackgroundType(BlockType.SenseHorizon);
            }
            foreach (CharacterBlock block in senseBlocks_vertical)
            {
                block.changeBackgroundType(BlockType.SenseVertical);
            }
        }

        /// <summary>
        /// 清除选中状态
        /// </summary>
        private void clearSelection()
        {
            // 选中了nochar block, 清楚select以及sense,恢复提示
            if (selectedBlock != null)
            {
                selectedBlock.changeBackgroundType(0);
                selectedBlock = null;
            }
            foreach (CharacterBlock block in senseBlocks_horizon)
            {
                block.changeBackgroundType(BlockType.Normal);
            }
            foreach (CharacterBlock block in senseBlocks_vertical)
            {
                block.changeBackgroundType(BlockType.Normal);
            }
            setToDefaultTip();
        }

        private void setToDefaultTip()
        {
            txtHorizonTip.Text = "请点击选中空格在点击字母输入答案";
            txtVerticalTip.Text = string.Empty;
        }

        private void setTip(string hTip, string vTip)
        {
            if (!string.IsNullOrEmpty(hTip))
            {
                txtHorizonTip.Text = "横:" + hTip;
            }
            else
            {
                txtHorizonTip.Text = string.Empty;
            }
            if (!string.IsNullOrEmpty(vTip))
            {
                txtVerticalTip.Text = "竖:" + vTip;
            }
            else
            {
                txtVerticalTip.Text = string.Empty;
            }
        }

        private void InitStage(int stageIndex)
        {
            isPause = false;
            blocks = new CharacterBlock[10, 10];
            selectedBlock = null;
            senseBlocks_horizon = new List<CharacterBlock>();
            senseBlocks_vertical = new List<CharacterBlock>();

            this.cvsBlocks.Children.Clear();

            currentRow = -1;
            currentColumn = -1;

            // 创建对象矩阵
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    CharacterBlock block = new CharacterBlock();

                    Canvas.SetLeft(block, j * 44);
                    Canvas.SetTop(block, i * 44);

                    // 初始化均为不可用状态
                    block.changeBackgroundType(BlockType.NoChar);
                    block.Row = i;
                    block.Column = j;
                    blocks[i, j] = block;
                    cvsBlocks.Children.Add(block);
                }
            }
            try
            {
                setCharMatrix(stageIndex);
            }
            catch
            {
                MessageBox.Show("载入异常,请稍后再试", "错误", MessageBoxButton.OK);
                if (this.NavigationService.CanGoBack)
                {
                    this.NavigationService.GoBack();
                }
                return;
            }
            initTimer(stageIndex);
            setToDefaultTip();

            this.gridMask.Visibility = System.Windows.Visibility.Collapsed;
            if (StagePage.currentStagePage != null)
            {
                try
                {
                    StagePage.currentStagePage.SetLoadEnable();
                }
                catch
                { }
            }
        }

        /// <summary>
        /// 初始化时间
        /// </summary>
        /// <param name="stageIndex"></param>
        private void initTimer(int stageIndex)
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();

        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (!isPause)
            {
                saveSecondCount++;
                StageData stageData = StageManager.Instance.getCurrentStageData();
                stageData.TotalSeconds++;

                if (saveSecondCount >= 20)
                {
                    StageManager.Instance.saveStageDatas();
                    saveSecondCount = 0;
                }

                if (isShowingTip)
                {
                    tipSeconds--;
                    if (tipSeconds < 0)
                    {
                        this.bdrShowTip.Visibility = System.Windows.Visibility.Collapsed;
                        isShowingTip = false;
                    }
                }
            }
        }

        /// <summary>
        /// 根据数据源设置矩阵状态
        /// </summary>
        /// <param name="index"></param>
        private void setCharMatrix(int index)
        {
            // 读取矩阵数据，并设置矩阵状态
            MapInfo mapInfo;
            if (StageManager.Instance.mapInfos.ContainsKey(index))
            {
                mapInfo = StageManager.Instance.mapInfos[index];
            }
            else
            {
                mapInfo = WordMapLoader.LoadMap(index);
            }

            if (mapInfo == null)
            {
                MessageBox.Show("地图载入异常", "发生错误", MessageBoxButton.OK);
                this.NavigationService.GoBack();
            }
            else
            {

                StageData stageData;
                if (StageManager.Instance.stageDatas.ContainsKey(index))
                {
                    stageData = StageManager.Instance.stageDatas[index];
                }
                else
                {
                    stageData = new StageData();
                    StageManager.Instance.stageDatas[index] = stageData;
                }


                foreach (CharacterLocationInfo location in mapInfo.charLocationList)
                {

                    CharacterBlock aimBlock = blocks[location.row, location.column];
                    aimBlock.changeBackgroundType(BlockType.Normal);
                    if (location.orientationWordIndex >= 0 && mapInfo.wordList.Count > location.orientationWordIndex)
                    {
                        // 横向有数据
                        WordInfo word = mapInfo.wordList[location.orientationWordIndex];

                        try
                        {
                            aimBlock.setAimHorizon(word.pinyin.Substring(location.orientationCharIndex, 1), word.content.Substring(location.orientationCharIndex, 1));

                            // 设置Tip
                            aimBlock.HorizontalTip = word.tip;
                            aimBlock.HorizonWordIndex = location.orientationWordIndex;
                        }
                        catch
                        { }
                    }
                    if (location.verticalWordIndex >= 0 && mapInfo.wordList.Count > location.verticalWordIndex)
                    {

                        // 竖向
                        WordInfo word = mapInfo.wordList[location.verticalWordIndex];
                        try
                        {

                            aimBlock.setAimVertical(word.pinyin.Substring(location.verticalCharIndex, 1), word.content.Substring(location.verticalCharIndex, 1));

                            // 设置Tip
                            aimBlock.VerticalTip = word.tip;
                            aimBlock.VerticalWordIndex = location.orientationWordIndex;
                        }
                        catch
                        { }
                    }
                    // 根据历史完成情况进行设置
                    if (stageData != null)
                    {
                        int blockKey = location.row * 10 + location.column;
                        if (stageData.CharInfoList.ContainsKey(blockKey))
                        {
                            MatrixCharInfo info = stageData.CharInfoList[blockKey];
                            if (info != null)
                            {
                                if (info.IsComplete)
                                {
                                    aimBlock.setComplete();
                                }
                                else
                                {
                                    aimBlock.setShowChar(info.CharStr);
                                }
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 按下按钮之后的处理
        /// </summary>
        /// <param name="keyStr"></param>
        public void touchKey(String keyStr)
        {
            if (isPause)
            {
                return;
            }
            if (selectedBlock != null)
            {
                if (!selectedBlock.IsCompleted)
                {

                    // 首先判断是否是lamp
                    if (keyStr == "lamp")
                    {
                        if (StageManager.Instance.LampCount > 0)
                        {
                            selectedBlock.setComplete();
                            // 减少灯泡数量
                            StageManager.Instance.LampCount = StageManager.Instance.LampCount - 1;
                            keyboard.RefreshLampCount();
                        }
                        else
                        {
                            // 没有可用的灯泡了，提示用户可以点击广告或者进入积分墙获取灯泡
                            //ShowToast("亲，没有提示灯泡喽！每次解锁3个关卡可以赠送6个哦，加油！");
                            MessageBox.Show("亲，没有提示灯泡喽！完成一个关卡可以获得3个提示灯泡哦！");
                        }
                    }
                    else
                    {
                        selectedBlock.setShowChar(keyStr);
                    }

                    // 判断词条是否完全匹配，显示完整词条数据
                    processJudgeComplete(senseBlocks_horizon, true);
                    processJudgeComplete(senseBlocks_vertical, false);
                }
            }
            moveToNextSelectedBlock();
        }

        private void processJudgeComplete(List<CharacterBlock> senseList, bool isHorizon)
        {
            if (senseList.Count > 0)
            {
                bool isSuccess = true;
                foreach (CharacterBlock block in senseList)
                {
                    if (!block.isCorrectPy())
                    {
                        isSuccess = false;
                        break;
                    }
                }

                // 判断当前点
                if (isSuccess && selectedBlock.isCorrectPy())
                {
                    // 成功
                    selectedBlock.setComplete();
                    foreach (CharacterBlock block in senseList)
                    {
                        block.setComplete();
                    }
                    StageData sd = StageManager.Instance.getCurrentStageData();
                    sd.ComplateCount = sd.ComplateCount + 1;

                    if (sd.ComplateCount >= StageManager.Instance.mapInfos[StageManager.Instance.LastStage].wordsCount)
                    {
                        ShowToast("恭喜你完成了本关卡，送您3个提示灯泡！要继续努力哦");
                        StageManager.Instance.LampCount = StageManager.Instance.LampCount + 3;
                        keyboard.RefreshLampCount();
                    }

                    // 得分
                    addScore(sd);

                    //ShowTip
                    ShowScoreTip();
                }
            }
        }

        /// <summary>
        /// 显示提示信息
        /// </summary>
        /// <param name="message"></param>
        public static void ShowToast(String message)
        {
            ShowToast("提示", message, null);
        }

        /// <summary>
        /// 显示提示信息
        /// </summary>
        public static void ShowToast(String title, String message, BitmapImage icon)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                ToastPrompt toast = new ToastPrompt();
                toast.Title = title;
                toast.Message = message;
                toast.TextOrientation = System.Windows.Controls.Orientation.Horizontal;
                toast.ImageSource = icon;
                toast.Show();
            });
        }

        /// <summary>
        /// 显示得分ScoreTip
        /// </summary>
        private void ShowScoreTip()
        {
            int showTipBase = r.Next(12);
            if (showTipBase > 4 && showTipBase < 10)
            {
                isShowingTip = true;
                tipSeconds = 1;
                this.bdrShowTip.Visibility = System.Windows.Visibility.Visible;

                int tipIndex = r.Next(scoreStrs.Count);

                this.txtTipName.Text = scoreStrs[tipIndex];
            }
            else if (showTipBase >= 10)
            {
                isShowingTip = true;
                tipSeconds = 1;
                this.bdrShowTip.Visibility = System.Windows.Visibility.Visible;

                this.txtTipName.Text = "恭喜！获得1个提示道具";
                StageManager.Instance.LampCount = StageManager.Instance.LampCount + 1;
                keyboard.RefreshLampCount();
            }
        }


        private void moveToNextSelectedBlock()
        {
            try
            {
                // 根据上一次的移动动作，进行向下或者向右
                if (isPreviousRight)
                {
                    // 将选择移动至下个block，先向右，再向下
                    if (currentColumn < 9
                            && currentColumn >= 0
                            && currentRow >= 0 && currentRow < 10
                            && blocks[currentRow, currentColumn + 1].CurrentType != BlockType.NoChar)
                    {
                        changeSelectBlock(currentColumn + 1, currentRow);
                        isPreviousRight = true;
                    }
                    else if (currentRow < 9
                          && currentRow >= 0
                          && currentColumn >= 0 && currentColumn < 10
                          && blocks[currentRow + 1, currentColumn].CurrentType != BlockType.NoChar)
                    {
                        changeSelectBlock(currentColumn, currentRow + 1);
                        isPreviousRight = false;
                    }
                    else
                    {
                        clearSelection();
                    }
                }
                else
                {
                    // 将选择移动至下个block，先向下，再向右
                    if (currentRow < 9
                            && currentRow >= 0
                            && currentColumn >= 0 && currentColumn < 10
                            && blocks[currentRow + 1, currentColumn].CurrentType != BlockType.NoChar)
                    {
                        changeSelectBlock(currentColumn, currentRow + 1);
                        isPreviousRight = false;
                    }
                    else if (currentColumn < 9
                          && currentColumn >= 0
                          && currentRow >= 0 && currentRow < 10
                          && blocks[currentRow, currentColumn + 1].CurrentType != BlockType.NoChar)
                    {
                        changeSelectBlock(currentColumn + 1, currentRow);
                        isPreviousRight = true;
                    }
                    else
                    {
                        clearSelection();
                    }
                }
            }
            catch
            { }
        }

        private void addScore(StageData sd)
        {
            if (sd.TotalSeconds <= 200)
            {
                sd.Score += 800;
            }
            else if (sd.TotalSeconds <= 400)
            {
                sd.Score += +500;
            }
            else if (sd.TotalSeconds <= 600)
            {
                sd.Score += +200;
            }
            else
            {
                sd.Score += 100;
            }
        }


        private void btnPauseContinue_Click(object sender, RoutedEventArgs e)
        {
            if (isPause)
            {
                isPause = false;
                this.bdrPause.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void btnPauseReturn_Click(object sender, RoutedEventArgs e)
        {
            this.bdrPause.Visibility = System.Windows.Visibility.Collapsed;
            try
            {
                NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                NavigationService.Navigate(new Uri("/MainPage.xaml?fromloading=2", UriKind.Relative));
            }
        }

        private void btnPauseClearStageData_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("重玩将清空本关卡的记录，您确定吗？", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                StageManager.Instance.ClearCurrentStageDate();
                this.bdrPause.Visibility = System.Windows.Visibility.Collapsed;
                InitStage(StageManager.Instance.LastStage);
            }
        }

        #region msn广告

        MSNADSDK.AD.AdView adView;

        private void initMsnAd()
        {
            //banner
            adView = new MSNADSDK.AD.AdView();
            adView.Appid = "142948";
            adView.Adid = "147540";
            adView.SecretKey = "9850f60487da4622b4358622dbe175a7";
            adView.SizeForAd = MSNADSDK.AD.AdSize.Large;

            adView.AdRequestSuccessEvent += adView_AdRequestSuccessEvent;
            adView.AdRequestErrorEvent += adView_AdRequestErrorEvent;
            adView.AdSdkExceptionEvent += adView_AdSdkExceptionEvent;

            gridMsnAd.Children.Add(adView);
        }

        void adView_AdSdkExceptionEvent(object sender, MSNADSDK.AD.ADExceptionEventArgs e)
        {
            Dispatcher.BeginInvoke(() =>
            {
                if (adView != null && gridMsnAd.Children.Contains(adView))
                {
                    gridMsnAd.Children.Remove(adView);
                    adView = null;
                }
            });
        }

        void adView_AdRequestErrorEvent(object sender, MSNADSDK.AD.AdRequestStatesEventArgs args)
        {
            Dispatcher.BeginInvoke(() =>
            {
                if (adView != null && gridMsnAd.Children.Contains(adView))
                {
                    gridMsnAd.Children.Remove(adView);
                    adView = null;
                }
            });
        }

        void adView_AdRequestSuccessEvent(object sender, MSNADSDK.AD.AdRequestStatesEventArgs args)
        {
            //请求成功
            //隐藏微软广告
            Dispatcher.BeginInvoke(() =>
            {
                if (adControlMicrosoft != null)
                {
                    this.LayoutRoot.Children.Remove(adControlMicrosoft);
                    adControlMicrosoft = null;
                }
            });
        }

        #endregion

        #region 亿动广告

        SMAdBannerView banner;

        private void InitSmartMadAd()
        {
            //  实例化SmartMad Banner容器
            banner = new SMAdBannerView("90025538");
            //  设置Banner广告刷新过场动画类型(可选)
            banner.AdBannerAnimationType =
            SMAdBannerAnimationType.BANNER_ANIMATION_TYPE_FADEINOUT;
            //  设置Banner广告事件
            banner.AdBannerClicked += new EventHandler(banner_AdBannerClicked);
            //banner.AdBannerWillExpand += new EventHandler(banner_AdBannerWillExpand);
            //banner.AdBannerExpandClosed += new
            //EventHandler(banner_AdBannerExpandClosed);
            banner.AdBannerReceived += new EventHandler(banner_AdBannerReceived);
            banner.AdBannerReceiveFailed += new
            EventHandler<SMAdEventCode>(banner_AdBannerReceiveFailed);
            //banner.AdBannerPresentingScreen += new
            //EventHandler<SMAdEventCode>(banner_AdBannerPresentingScreen);
            //banner.AdBannerLeaveApplication += new
            //EventHandler(banner_AdBannerLeaveApplication);
            //banner.AppWillSuspendForAd += new
            //EventHandler(banner_AppWillSuspendForAd);
            //banner.AppWillResumeFromAd += new
            //EventHandler(banner_AppWillResumeFromAd);
            //banner.AdBannerDismissScreen += new
            //EventHandler(banner_AdBannerDismissScreen);
            //  将Banner容器加入界面
            gridMsnAd.Children.Add(banner);
        }

        private void banner_AdBannerReceiveFailed(object sender, SMAdEventCode e)
        {
            Dispatcher.BeginInvoke(() =>
            {
                if (banner != null && gridMsnAd.Children.Contains(banner))
                {
                    gridMsnAd.Children.Remove(banner);
                    banner = null;
                }
            });
        }

        private void banner_AdBannerReceived(object sender, EventArgs e)
        {
            //接收成功，隐藏微软广告
            Dispatcher.BeginInvoke(() =>
            {
                if (adControlMicrosoft != null)
                {
                    this.LayoutRoot.Children.Remove(adControlMicrosoft);
                    adControlMicrosoft = null;
                }
            });
        }

        private void banner_AdBannerClicked(object sender, EventArgs e)
        {

        }

        private void imgBanner_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            if (currentMokaAdIndex == 0)
            {
                //跳转到魔卡幻想
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=c035da4065183dbec79ffbe43fa11301ac619c2b8fdd723b692ae4b7915b3ce7", UriKind.Absolute);
            }
            else
            {
                //跳转到千魔斩
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=5fc22bb64e05cb93477f153d9d61cb409179c3036db5ba85446dde582ec3c345", UriKind.Absolute);
            }
            webBrowserTask.Show();
        }

        #endregion
    }
}